package com.liaoban.app.ui.anchor;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.liaoban.app.R;
import com.liaoban.app.adapter.AnchorPhotoAdapter;
import com.liaoban.app.adapter.AnchorVideoAdapter;
import com.liaoban.app.adapter.AnchorGiftAdapter;
import com.liaoban.app.adapter.GlideImageLoader;
import com.liaoban.app.api.type.Anchor;
import com.liaoban.app.api.type.comment.BaseResponse;
import com.liaoban.app.api.type.request.WuserinfoRequest;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ConfigKey;
import com.liaoban.app.constants.ExtraParam;
import com.liaoban.app.helper.ConfigHelper;
import com.liaoban.app.helper.ImageHelper;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.base.BaseActivity;
import com.liaoban.app.ui.login.LoginActivity;
import com.liaoban.app.ui.mine.FansActivity;
import com.liaoban.app.ui.mine.VideoCertActivity;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.util.TakePictureManager;
import com.liaoban.neliveplay.MainActivity;
import com.liaoban.neliveplay.activity.NEVideoPlayerActivity;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.activity.AVChatActivity;
import com.netease.nim.demo.session.SessionHelper;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.youth.banner.Banner;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.http.Body;

/**
 * 主播详情
 */
public class AnchorDetailActivity extends BaseActivity {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_grade)
    ImageView ivGrade;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.tv_wuser_num)
    TextView tvWuserNum;
    @BindView(R.id.iv_sex)
    ImageView ivSex;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.wuser_id)
    TextView tvWuserId;
    @BindView(R.id.tv_description)
    TextView tvDesc;
    @BindView(R.id.iv_follow)
    ImageView ivFollow;
    @BindView(R.id.rv_gift)
    RecyclerView rvGift;
    @BindView(R.id.rv_video)
    RecyclerView rvVideo;
    @BindView(R.id.rv_photo)
    RecyclerView rvPhoto;
    @BindView(R.id.iv_banner_video)
    ImageView ivBannerVideo;
    @BindView(R.id.layout_gift)
    LinearLayout layoutGift;
    @BindView(R.id.layout_rv_video)
    LinearLayout layoutRvVideo;
    @BindView(R.id.layout_photo)
    LinearLayout layoutPhoto;
    @BindView(R.id.view_line1)
    View viewLine1;
    @BindView(R.id.layout_gift_large)
    LinearLayout layoutGiftLarge;
    @BindView(R.id.view_line2)
    View viewLine2;
    @BindView(R.id.layout_video_phone_large)
    LinearLayout layoutVideoPhoneLarge;
    @BindView(R.id.tv_video_title)
    TextView tvVideoTitle;
    @BindView(R.id.tv_photo_title)
    TextView tvPhotoTitle;
    @BindView(R.id.layout_chat)
    LinearLayout layoutChat;
    @BindView(R.id.layout_video)
    LinearLayout layoutVideo;
    @BindView(R.id.layout_voice)
    LinearLayout layoutVoice;
    @BindView(R.id.tv_follow)
    TextView tvFollow;
    @BindView(R.id.layout_wuser_status)
    LinearLayout layoutWuserStatus;
    @BindView(R.id.tv_tong_rule)
    TextView tvTongRule;
    @BindView(R.id.tv_yu_rule)
    TextView tvYuRule;
    @BindView(R.id.tv_jietong)
    TextView tvJieTong;
    @BindView(R.id.layout_bottom)
    View layout_bottom;
    @BindView(R.id.layout_bottom_shenhe)
    View layout_bottom_shenhe;

    private String mWuserId; //有可能为空
    private String mImId; //有可能为空
    private Anchor mAnchor;
    private AnchorGiftAdapter mGiftAdapter;
    private AnchorVideoAdapter mAnchorVideoAdapter;
    private AnchorPhotoAdapter mAnchorPhotoAdapter;

    public static Intent newIntent(Context context, String wuserId) {
        Intent intent = new Intent(context, AnchorDetailActivity.class);
        intent.putExtra(ExtraParam.ID, wuserId);
        return intent;
    }

    public static Intent newIntentImId(Context context, String imId) {
        Intent intent = new Intent(context, AnchorDetailActivity.class);
        intent.putExtra(ExtraParam.ID1, imId);
        return intent;
    }

    @Override
    protected int getLayoutResID() {
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_anchor_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mWuserId = getIntent().getStringExtra(ExtraParam.ID);
        mImId = getIntent().getStringExtra(ExtraParam.ID1);
        String version_check = ConfigHelper.getString(this, ConfigKey.VERSION_CHECK);
        if ("1".equals(version_check)) {
            layout_bottom_shenhe.setVisibility(View.VISIBLE);
            layout_bottom.setVisibility(View.GONE);
        } else {
            layout_bottom_shenhe.setVisibility(View.GONE);
            layout_bottom.setVisibility(View.VISIBLE);
        }
        layoutChat.setSelected(false);
        layoutVideo.setSelected(false);
        layoutVoice.setSelected(false);
        initBanner();
        initGift();
        initAnchorVideo();
        initAnchorPhoto();
        loadData();
    }

    /**
     * 初始化轮播图
     */
    private void initBanner() {
        banner.setOnBannerListener(position -> {
            Anchor.ImgBean imgBean = mAnchor.getImg().get(position);
            if (Anchor.TYPE_VIDEO == imgBean.getImgType()) { //视频
                CommonUtils.startNeVideo(this, imgBean.getVideoSrc());
            } else {
                List<Anchor.ImgBean> imgBeans = mAnchor.getImg();
                List<String> imgs = new ArrayList<>(); //图片列表
                for (Anchor.ImgBean imgBean1 : imgBeans) {
                    if (Anchor.TYPE_VIDEO != imgBean1.getImgType()) { //图片
                        imgs.add(CommonUtils.getFullPic(imgBean1.getImgSrc()));
                    }
                }
                int pos = position - (imgBeans.size() - imgs.size()); //点击的图片在图片列表中的位置
                //startActivity(GalleryActivity.newIntent(this, imgs, pos));
                startActivity(ImgBannerActivity.newIntent(this, imgs, pos));
            }
        });
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Anchor.ImgBean imgBean = mAnchor.getImg().get(position);
                if (Anchor.TYPE_VIDEO == imgBean.getImgType()) {
                    if (ivBannerVideo != null) {
                        ivBannerVideo.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (ivBannerVideo != null) {
                        ivBannerVideo.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initGift() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvGift.setLayoutManager(manager);
        mGiftAdapter = new AnchorGiftAdapter(null);
        rvGift.setAdapter(mGiftAdapter);
        rvGift.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                layoutGift.performClick();  //模拟父控件的点击
            }
            return false;
        });
    }

    private void initAnchorVideo() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvVideo.setLayoutManager(manager);
        mAnchorVideoAdapter = new AnchorVideoAdapter(null);
        rvVideo.setAdapter(mAnchorVideoAdapter);
        rvVideo.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                layoutRvVideo.performClick();  //模拟父控件的点击
            }
            return false;
        });
    }

    private void initAnchorPhoto() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvPhoto.setLayoutManager(manager);
        mAnchorPhotoAdapter = new AnchorPhotoAdapter(null);
        rvPhoto.setAdapter(mAnchorPhotoAdapter);
        rvPhoto.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                layoutPhoto.performClick();  //模拟父控件的点击
            }
            return false;
        });
    }

    private void loadData() {
        showRunningDialog();
        WuserinfoRequest wuserinfoRequest = new WuserinfoRequest();
        if (!TextUtils.isEmpty(mWuserId)) {
            wuserinfoRequest.setWuserId(mWuserId);
            startTask(CommonBiz.getInstance().wuserinfo(wuserinfoRequest), anchorBaseResponse -> {
                processDetailView(anchorBaseResponse);
            });
        } else {
            wuserinfoRequest.setImId(mImId);
            startTask(CommonBiz.getInstance().imUserInfo(wuserinfoRequest), anchorBaseResponse -> {
                processDetailView(anchorBaseResponse);
            });
        }

    }

    private void processDetailView(BaseResponse<Anchor> anchorBaseResponse) {
        mAnchor = anchorBaseResponse.data;
        List<String> banners = new ArrayList<>();
        for (Anchor.ImgBean imgBean : mAnchor.getImg()) {
            banners.add(CommonUtils.getFullPic(imgBean.getImgSrc()));
        }
        banner.setImages(banners).setImageLoader(new GlideImageLoader()).start();
        if (mAnchor.getLineStatus() == 1) { //空闲
            tvStatus.setBackgroundResource(R.drawable.shape_yellow_rectangle);
        }
        if (mAnchor.getLineStatus() == 2) {//勿扰
            tvStatus.setBackgroundResource(R.drawable.shape_gray_rectangle);
        }
        if (mAnchor.getLineStatus() == 3) {//忙碌
            tvStatus.setBackgroundResource(R.drawable.shape_red_rectangle);
        }
        tvStatus.setText(CommonUtils.getLineStatusName(mAnchor.getLineStatus()));
        tvName.setText(mAnchor.getWuserName());
        ivGrade.setImageResource(CommonUtils.getRecommendGradeRes(mAnchor.getWuserGrade()));
        tvAge.setText(String.valueOf(mAnchor.getAge()));
        tvWuserNum.setText(String.valueOf(mAnchor.getWuserNum()));
        tvWuserId.setText("ID:" + mAnchor.getWuserId());
        tvDesc.setText(mAnchor.getDescription());
        if (0 == mAnchor.getFansIsStatus()) {
            ivFollow.setImageResource(R.mipmap.ic_follow_she);
        } else if (1 == mAnchor.getFansIsStatus()) {
            ivFollow.setImageResource(R.mipmap.ic_has_follow);
        } else if (2 == mAnchor.getFansIsStatus()) {
            ivFollow.setImageResource(R.mipmap.ic_fh);
        }
        ivSex.setImageResource(mAnchor.getWuserSex() == 1 ? R.mipmap.ic_girl : R.mipmap.ic_boy);
        Anchor.InfoBean infoBean = mAnchor.getInfos();
        if (infoBean != null) {
            tvCity.setText(infoBean.getCity() + "  " + infoBean.getJuli() + "km");
        }
        if (!CommonUtils.isEmpty(mAnchor.getGift())) {
            viewLine1.setVisibility(View.VISIBLE);
            layoutGiftLarge.setVisibility(View.VISIBLE);
            mGiftAdapter.setNewData(mAnchor.getGift());
        }
        if (!CommonUtils.isEmpty(mAnchor.getVideo()) || !CommonUtils.isEmpty(mAnchor.getIssue())) {
            viewLine2.setVisibility(View.VISIBLE);
            layoutVideoPhoneLarge.setVisibility(View.VISIBLE);
            if (!CommonUtils.isEmpty(mAnchor.getVideo())) {
                tvVideoTitle.setVisibility(View.VISIBLE);
                layoutRvVideo.setVisibility(View.VISIBLE);
                mAnchorVideoAdapter.setNewData(mAnchor.getVideo());
            }
            if (!CommonUtils.isEmpty(mAnchor.getIssue())) {
                tvPhotoTitle.setVisibility(View.VISIBLE);
                layoutPhoto.setVisibility(View.VISIBLE);
                mAnchorPhotoAdapter.setNewData(mAnchor.getIssue());
            }
        }
        if (!mAnchor.isTongStatus()) {
            layoutChat.setSelected(true);
        }
        if (1 == mAnchor.getCallStatus()) {
            layoutVideo.setSelected(true);
            layoutVoice.setSelected(true);
        }
        tvFollow.setText(String.valueOf(mAnchor.getFollowNum()));
        if (1 == mAnchor.getWuserStatus()) {
            layoutWuserStatus.setVisibility(View.VISIBLE);
            tvTongRule.setText(mAnchor.getTongRule() + "聊币分钟");
            tvYuRule.setText(mAnchor.getYuRule() + "聊币分钟");
            //tvJieTong.setText(mAnchor.getJietong());
        } else {
            layoutWuserStatus.setVisibility(View.GONE);
        }
            /*List<String> labels = new ArrayList<>();
            labels.add("性感");
            labels.add("态度好");
            labels.add("身材一流");
            labelsView.setLabels(labels, (label, position, data) -> data);*/
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.layout_chat)
    public void chat() {
        //startActivity(new Intent(this, com.netease.nim.demo.main.activity.MainActivity.class));
        if (!CommonBiz.getInstance().isLogin(this)) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        if (mAnchor == null || mAnchor.isTongStatus()) {
            return;
        }
        SessionHelper.startP2PSession(this, /*"13681517817"*/mAnchor.getWuserImId());
    }

    @OnClick({R.id.layout_bottom_shenhe, R.id.layout_voice})
    public void voice() {
        if (!CommonBiz.getInstance().isLogin(this)) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        if (mAnchor == null || 1 != mAnchor.getCallStatus()) {
            //ToastHelper.show(this, R.string.im_null_tip);
            return;
        }
        AVChatKit.outgoingCall(this, mAnchor.getWuserImId()/*"yubachang2012"*/, UserInfoHelper.getUserDisplayName(mAnchor.getWuserImId()/*"yubachang2012"*/), AVChatType.AUDIO.getValue(), AVChatActivity.FROM_INTERNAL);
    }

    @OnClick(R.id.layout_video)
    public void video() {
        if (!CommonBiz.getInstance().isLogin(this)) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        if (mAnchor == null || 1 != mAnchor.getCallStatus()) {
            //ToastHelper.show(this, R.string.im_null_tip);
            return;
        }
        AVChatKit.outgoingCall(this, mAnchor.getWuserImId()/*"yubachang2012"*/, UserInfoHelper.getUserDisplayName(mAnchor.getWuserImId()/*"yubachang2012"*/), AVChatType.VIDEO.getValue(), AVChatActivity.FROM_INTERNAL);
    }

    /*@OnClick({R.id.tv_wuser_num, R.id.tv_wuser_num_tip})
    public void wuserNum() {
        if (mAnchor != null && 1 == mAnchor.getInfo()) { //是自己可以查看粉丝
            startActivity(new Intent(this, FansActivity.class));
        }
    }*/

    @OnClick(R.id.iv_follow)
    public void follow() {
        if (mAnchor == null) {
            return;
        }
        showRunningDialog(R.string.committing);
        WuserinfoRequest wuserinfoRequest = new WuserinfoRequest();
        wuserinfoRequest.setWuserId(mAnchor.getWuserId() + "");
        startTask(CommonBiz.getInstance().follow(wuserinfoRequest), baseResponse -> {
            if (0 == baseResponse.code) {
                ivFollow.setImageResource(R.mipmap.ic_follow_she);
            } else if (1 == baseResponse.code) {
                ivFollow.setImageResource(R.mipmap.ic_has_follow);
            } else if (2 == baseResponse.code) {
                ivFollow.setImageResource(R.mipmap.ic_fh);
            }
            ToastHelper.show(AnchorDetailActivity.this, baseResponse.msg);
        });
    }

    @OnClick({R.id.layout_photo})
    public void photo() {
        if (mAnchor == null) {
            return;
        }
        //startActivity(PhotoActivity.newIntent(this, mAnchor.getWuserId() + ""));
        List<Anchor.IssueBean> issueBeans = mAnchor.getIssue();
        List<String> pics = new ArrayList<>();
        for (Anchor.IssueBean issueBean : issueBeans) {
            pics.add(CommonUtils.getFullPic(issueBean.getImgSrc()));
        }
        startActivity(ImgBannerActivity.newIntent(this, pics, 0));
    }

    @OnClick(R.id.layout_rv_video)
    public void rvVideo() {
        if (mAnchor == null) {
            return;
        }
        startActivity(VideoActivity.newIntent(this, mAnchor.getWuserId() + ""));
    }

    @OnClick(R.id.layout_gift)
    public void gift() {
        if (mAnchor == null) {
            return;
        }
        startActivity(GiftActivity.newIntent(this, mAnchor.getWuserId() + ""));
    }

    @OnClick(R.id.iv_report)
    public void report() {
        showReportDialog();
    }

    /**
     * 举报
     */
    private void showReportDialog() {
        View view = getLayoutInflater().inflate(
                R.layout.dialog_report, null);
        final Dialog dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        TextView tvReport = view.findViewById(R.id.tv_report);
        tvReport.setOnClickListener(v -> {
            dialog.dismiss();
            if (mAnchor == null) {
                return;
            }
            startActivity(ReportActivity.newIntent(this, mAnchor.getWuserId() + ""));
        });
        TextView tvBlackList = view.findViewById(R.id.tv_black_list);
        if (mAnchor != null) {
            tvBlackList.setText(mAnchor.getBlackStatus() == 0 ? "加入黑名单" : "移出黑名单");
        }
        tvBlackList.setOnClickListener(v -> {
            dialog.dismiss();
            if (mAnchor == null) {
                return;
            }
            showRunningDialog(R.string.committing);
            WuserinfoRequest wuserinfoRequest = new WuserinfoRequest();
            wuserinfoRequest.setWuserId(mAnchor.getWuserId() + "");
            startTask(CommonBiz.getInstance().wuserBlack(wuserinfoRequest), baseResponse -> {
                ToastHelper.show(this, baseResponse.msg);
                if (1 == baseResponse.code) {
                    mAnchor.setBlackStatus(mAnchor.getBlackStatus() == 0 ? 1 : 0);
                }
            });
        });
        TextView tvCancel = view.findViewById(R.id.tv_to_cancel);
        tvCancel.setOnClickListener(v -> dialog.dismiss());
    }
}
